package com.example.webrestfulcrud.exception;

import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 在容器中加入自己的ErrorAttributes，替换自动配置的
 * 在保留原有功能的基础上添加自定义的属性，直接继承即可
 */
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
    /**
     * @param webRequest spring将HttpServletRequest进行了包装，在这里可以直接当成HttpServletRequest来用
     * @param options
     * @return 返回值map就是json能获取的所有字段
     */
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {


        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options);

        errorAttributes.put("myErrorField", "这样就可以随便放入数据了");


        /**
         * 获取 MyCustomizedBasicErrorController 放入request的属性
         * 我们自定义异常处理器所携带的数据
         */
        Map<String, Object> attributeMap = (Map<String, Object>) webRequest.getAttribute(MyUserNotExistExceptionHandler.MY_ERROR_MAP, RequestAttributes.SCOPE_REQUEST);
        if (attributeMap != null) {
            /**
             * 这种写法太偷懒了
             * errorAttributes.put("request带来的参数",attributeMap);
             */
            Set<Map.Entry<String, Object>> entries = attributeMap.entrySet();

            Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = iterator.next();
                errorAttributes.put(next.getKey(), next.getValue());
            }
        }


        return errorAttributes;
    }
}
